package com.future.message.Service.Impl;

import com.future.message.Mapper.DataMapper;
import com.future.message.Mapper.RelevantReportMapper;
import com.future.message.Mapper.UserMapper;
import com.future.message.Service.DataService;
import com.future.message.Service.UserService;
import com.future.message.Utils.ResponseResult;
import com.future.message.configuration.Security.WebSecurityConfig;
import com.future.message.pojo.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.parameters.P;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private RelevantReportMapper relevantReportMapper;

    @Resource
    private DataMapper dataMapper;

    @Resource
    private DataService dataService;

    /**
     * 延迟加载
     */
    @Lazy
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public ResponseResult addUser(User user) {
        String account = user.getAccount();
        String password = user.getPassword();
        String nickName = user.getNickName();
        String department = user.getDepartment();
        user.setGrade(0);
        user.setPassword(passwordEncoder.encode(password));
        if (account == null || account.length() < 6 || account.length() > 16){
            return ResponseResult.error("账号不合法，请重新添加！");
        }
        if (department == null){
            return ResponseResult.error("部门不能为空！");
        }
        if (userMapper.judgeDepartment(department) != 0){
            return ResponseResult.error("部门已存在！");
        }
        if (userMapper.selectByUserName(account) != null){
            return ResponseResult.error("账号已存在！");
        }
        if (password == null || password.length() < 6 || password.length() > 16){
            return ResponseResult.error("密码不合法，请重新输入！");
        }
        if (nickName == null){
            return ResponseResult.error("用户昵称不合法！");
        }
        if (userMapper.addUser(user) == 1){
            return ResponseResult.success("添加成功！");
        }
        return ResponseResult.error("添加失败，请稍后重试！");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult deleteUser(Integer userId) {
        if (userId == null){
            return ResponseResult.error("用户信息不存在！");
        }
        int i = userMapper.deleteUser(userId);
        relevantReportMapper.deleteRelevantByUserId(userId);
        List<Data> datas = dataMapper.findDataByUserId(userId);
        List<Integer> c= datas.stream().map(Data::getDataId).collect(Collectors.toList());
        for(int x: c){
            dataService.deleteData(x);
        }
        if (i == 1){
            return ResponseResult.success("删除成功！");
        }else{
            return ResponseResult.error("服务器繁忙，请稍后尝试！");
        }
    }

    @Override
    public ResponseResult updateUser(User user) {
        if (user == null){
            return ResponseResult.error("数据为空，请重新输入！");
        }
        String account = user.getAccount();
        String password = user.getPassword();
        String nickName = user.getNickName();
        Integer userId = user.getUserId();
        String department = user.getDepartment();
        if (userId == null){
            return ResponseResult.error("用户信息不合法！");
        }
        User oldUser = userMapper.findUserById(userId);
        if (oldUser == null){
            return ResponseResult.error("用户信息不存在！");
        }
        if (account != null){
            User userAccount = userMapper.selectByUserName(account);
            System.out.println(userAccount);
            if ( userAccount != null && !userAccount.getUserId().equals(oldUser.getUserId())){
                return ResponseResult.error("账号已存在！");
            }
            if (account.length() < 6 || account.length() > 16){
                return ResponseResult.error("账号不合法，请重新输入！");
            }else{
                oldUser.setAccount(account);
            }
        }
        if (password != null){
            if (password.length() < 6 || password.length() > 16){
                return ResponseResult.error("密码不合法！");
            }else{
                oldUser.setPassword(passwordEncoder.encode(password));
            }
        }
        if (nickName != null){
            oldUser.setNickName(nickName);
        }
        if (department != null && !department.equals(oldUser.getDepartment())){
            if (userMapper.judgeDepartment(department) != 0){
                return ResponseResult.error("部门已经存在！");
            }
        }
        if (userMapper.updateUser(oldUser) == 1){
            return ResponseResult.success("更新成功！");
        }
        return ResponseResult.error("更新失败，请稍后重试！");
    }

    @Override
    public ResponseResult queryUserByPage(Integer pageNow, Integer pageSize) {
        PageHelper.startPage(pageNow,pageSize);
        List<UserVo> users = userMapper.queryUserByPage();
//        for (UserVo userVo:users) {
//            Integer all = userMapper.countReportAll(userVo.getUserId());
//            Integer finish = userMapper.countReportFinish(userVo.getUserId());
//            userVo.setReportCount(all);
//            userVo.setFinish(finish+"/"+all);
//        }
        PageInfo<UserVo> pageInfo = new PageInfo<UserVo>(users);
        return ResponseResult.success(pageInfo);
    }

    @Override
    public ResponseResult vagueSearch(String message,Integer pageNow,Integer pageSize) {
        PageHelper.startPage(pageNow,pageSize);
        List<UserVo> users = userMapper.vagueSearch(message);
//        for (UserVo userVo:users) {
//            Integer all = userMapper.countReportAll(userVo.getUserId());
//            Integer finish = userMapper.countReportFinish(userVo.getUserId());
//            userVo.setReportCount(all);
//            userVo.setFinish(finish+"/"+all);
//        }
        PageInfo<UserVo> pageInfo = new PageInfo<>(users);
        return ResponseResult.success(pageInfo);
    }

    /**
     * 查询用户权限
     * @return
     */
    @Override
    public String queryForPermission(String username){
        return userMapper.queryForPermission(username);
    }

    /**
     * 通过用户id查找
     * @param userId
     * @return
     */
    @Override
    public ResponseResult searchByUserId(Integer userId) {
        User user = userMapper.searchByUserId(userId);
        return ResponseResult.success(user);
    }

    @Override
    public ResponseResult modifyDetail(Integer userId,String nickedName) {
        int i = userMapper.modifyDetail(userId, nickedName);
        if (i == 1){
            return ResponseResult.success("修改成功！");
        }
        return ResponseResult.error("修改失败！");
    }

    @Override
    public ResponseResult modifyPassword(Integer userId,String oldPassword, String newPassword) {
        String password = userMapper.findUserById(userId).getPassword();
        if (passwordEncoder.matches(oldPassword,password)){
            log.info("用户:"+userId+"    修改密码！");
            int i = userMapper.modifyPassword(userId, passwordEncoder.encode(newPassword));
            if (i == 1){
                return ResponseResult.success("修改成功！");
            }else{
                return ResponseResult.error("服务器繁忙，请稍后重试！");
            }
        }
        return ResponseResult.error("旧密码错误！");
    }

    @Override
    public SecurityUser queryByUserName(String username) {
        User user = userMapper.selectByUserName(username);
        if (user == null){
            throw new UsernameNotFoundException("账号不存在！");
        }
        List<String> list = new ArrayList<>();
        list.add(user.getGrade()+"");
        SecurityUser securityUser = new SecurityUser(user, list);
        return  securityUser;
    }

    @Override
    public ResponseResult queryForAllUser() {
        return ResponseResult.success(userMapper.queryForAll());
    }

}
